package com.tubeilike.model;

import java.util.List;

import javax.jdo.PersistenceManager;

import javax.jdo.Query;
import com.tubeilike.entity.Tube;

public class TubeModel {

	static PersistenceManager pm = PMF.get().getPersistenceManager();

	public static void initPm() {
		if (pm.isClosed()) {
			pm = PMF.get().getPersistenceManager();
		}
	}

	public static boolean add(Tube tube) {
		initPm();
		try {
			pm.makePersistent(tube);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean addAll(List<Tube> listTube) {
		initPm();
		try {
			pm.makePersistentAll(listTube);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public static boolean update(Tube tube) {
		initPm();
		pm.makePersistent(tube);
		return true;
	}

	@SuppressWarnings("unchecked")
	public static Tube getByTubeId(String tubeId) {
		initPm();
		Tube tube = null;
		Query query = pm.newQuery(Tube.class);
		query.setFilter("tubeId=='" + tubeId + "' && status==1");
		query.setRange(0, 1);
		List<Tube> listResult = (List<Tube>) query.execute();
		if (listResult.size() > 0) {
			tube = listResult.get(0);
		}
		return tube;
	}

	@SuppressWarnings("unchecked")
	public static List<Tube> getTop10View() {
		initPm();
		Query query = pm.newQuery(Tube.class);
		query.setFilter("status==1");
		query.setOrdering("viewCount desc");
		query.setRange(0, 10);
		List<Tube> listResult = (List<Tube>) query.execute();
		return listResult;
	}

	@SuppressWarnings("unchecked")
	public static List<Tube> getByCategory(String alias, int page,
			int itemPerPage) {
		initPm();
		page = page - 1;
		Query query = pm.newQuery(Tube.class);
		query.setFilter("categoryAlias=='" + alias + "' && status==1");
		query.setOrdering("catePosition asc");
		query.setRange(itemPerPage * page, itemPerPage * page + itemPerPage);
		return (List<Tube>) query.execute();
	}

	@SuppressWarnings("unchecked")
	public static List<Tube> getAllByCategory(String alias) {
		initPm();
		Query query = pm.newQuery(Tube.class);
		query.setFilter("categoryAlias=='" + alias + "' && status==1");
		query.setOrdering("catePosition asc");
		return (List<Tube>) query.execute();
	}

	public static void closePM() {
		pm.close();
	}
}
